package com.blue.wechat.invoke.spi.media;

import java.io.File;
import java.io.FileOutputStream;

import org.apache.commons.io.IOUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blue.core.dict.HttpMethod;
import com.blue.core.dict.WechatMediaType;
import com.blue.core.util.JsonUtil;
import com.blue.core.util.UUID;
import com.blue.core.util.UrlUtil;
import com.blue.http.client.DownloadResult;
import com.blue.http.util.HttpException;
import com.blue.wechat.cache.Wechat;
import com.blue.wechat.invoke.BaseInvoker;
import com.blue.wechat.invoke.WechatInvokeUtil;
import com.blue.wechat.invoke.WechatInvoker;
import com.blue.wechat.invoke.annotation.WechatUrl;
import com.blue.wechat.invoke.model.media.GetMaterial;

/**
 * 获取永久素材总数
 * 
 * @author zhengj
 * @since 1.0 2017年6月10日
 */
@WechatUrl(WechatInvoker.GET_MATERIAL)
public class GetMaterialInvoker extends BaseInvoker<GetMaterial>
{
	private static Logger logger = LoggerFactory.getLogger(GetMaterialInvoker.class);
	
	public GetMaterialInvoker()
	{
	}

	@Override
	protected WechatInvoker getInvoker()
	{
		return WechatInvoker.GET_MATERIAL;
	}
	
	@Override
	protected String invoke(String url, HttpMethod method, Object post) throws Exception
	{
		JSONObject param = new JSONObject();
		param.put("media_id", post);
		CloseableHttpClient httpClient = httpInvoker.getHttpClient();
		HttpPost request = new HttpPost(url);
		StringEntity entityPost = new StringEntity(param.toJSONString(), Consts.UTF_8);
		request.setEntity(entityPost);
		
		GetMaterial material = new GetMaterial();
		String json = null;
		String path = UrlUtil.getTempDir() + UUID.generator();
		try (CloseableHttpResponse response = httpClient.execute(request);)
		{
			StatusLine statusLine = response.getStatusLine();
			if (statusLine.getStatusCode() != HttpStatus.SC_OK) // http调用失败
				throw new HttpException(statusLine.getStatusCode(), "下载失败：" + statusLine.getReasonPhrase());
			
			HttpEntity entity = response.getEntity();
			if (!entity.isStreaming())
				throw new HttpException(HttpStatus.SC_INTERNAL_SERVER_ERROR, "下载失败：" + EntityUtils.toString(entity, Consts.UTF_8));
				
			material.setSize((int)entity.getContentLength());
			WechatMediaType type = WechatInvokeUtil.geMediaType(entity, response);
			if (type != null)
			{
				material.setType(type);
				if (type == WechatMediaType.IMAGE)
					path += ".jpg";
				else if (type == WechatMediaType.VOICE)
					path += ".amr";
			}
			material.setPath(path);
			if (type != null)
			{
				File file = new File(path);
				try (FileOutputStream fos = new FileOutputStream(file);)
				{
					entity.writeTo(fos);
				}
				return JsonUtil.output(material);
			}
			else
			{
				json = IOUtils.toString(entity.getContent(), "UTF-8");
				logger.info("下载为 json 数据：{}", json);
			}
		}

		if (json.contains("\"news_item\":")) // 图文素材
			return json;
		
		if (json.contains("\"errcode\":")) // 错误
			return json;
		
		JSONObject object = JSON.parseObject(json);
		String video = object.getString("down_url");
		material.setTitle(object.getString("title"));
		material.setDescription(object.getString("description"));
		logger.info("视频地址：{}", video);
		path = UrlUtil.getTempDir() + UUID.generator() + ".mp4";
		File file = new File(path);
		DownloadResult result = httpInvoker.download(video, file);
		material.setType(WechatMediaType.VIDEO);
		material.setMimeType(result.getMimeType());
		material.setSize(result.getSize());
		material.setPath(path);
		return JsonUtil.output(material);
		
	}

	@Override
	protected GetMaterial handleSuccess(String resp, Wechat wechat)
	{
		GetMaterial gm = JSON.parseObject(resp, GetMaterial.class);
		return gm;
	}
}
